package me.numark.fragments;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.marshalchen.ultimaterecyclerview.UltimateViewAdapter;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import me.numark.R;
import me.numark.activities.ChatActivity;
import me.numark.activities.ProfileActivity;
import me.numark.net.BaseResponse;
import me.numark.net.NetworkConstants;
import me.numark.net.RequestServerTask;
import me.numark.providers.DatabaseHelper;
import me.numark.providers.Numa;
import me.numark.utils.Constants;
import me.numark.utils.Global;
import me.numark.utils.HttpUtil;
import me.numark.utils.MessageUtils;
import me.numark.utils.Utils;
import me.numark.view.BaseViewHolder;
import me.numark.view.ChatItemClickListener;
import me.numark.view.CircleImageView;

/**
 * Created by Evan on 15/8/8.
 */
public class NoticeMsgFragment extends BaseListFragment implements LoaderManager.LoaderCallbacks<Cursor>,ChatItemClickListener {

    SimpleAdapter mMsgAdapter;
    Cursor delCursor;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dataList = new ArrayList();
        mMsgAdapter = new SimpleAdapter(this, null);
        mMsgAdapter.setOnItemLongClickListener(this);
        mAdapter = mMsgAdapter;

    }

    @Override
    public void initUI(View view) {
        super.initUI(view);
        recyclerView.setBackgroundColor(Color.WHITE);
        getLoaderManager().initLoader(0, null, this);
        setHasMore(true);
        mAdapter.setCustomLoadMoreView(null);
        recyclerView.setEmptyView(0);

    }

    @Override
    public void loadMore(int itemsCount, int maxLastVisiblePosition) {
        super.loadMore(itemsCount, maxLastVisiblePosition);
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                long time = Constants.BIG_TIME;
                int id = 0;
                Cursor cursor = mMsgAdapter.mCursor;
                delCursor = mMsgAdapter.mCursor;
                int count = cursor.getCount();
                if (count > 0) {
                    cursor.moveToPosition(count - 1);
                    time = cursor.getLong(cursor.getColumnIndex("last_time"));
                    id = cursor.getInt(cursor.getColumnIndex("_id"));
                }
                MessageUtils.loadMoreDialogs(getActivity().getContentResolver(), time, id);
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                endRefreshing();
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    @Override
    public void onRefresh() {
        super.onRefresh();
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                MessageUtils.msgUpdate(getActivity());
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                endRefreshing();
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }


    @Override
    protected void addDataToList(BaseResponse response, boolean isNew) {

    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return new CursorLoader(getActivity(), Numa.DialogColumns.CONTENT_URI, null, "_id>0", null,
                "last_time desc, _id desc");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        mMsgAdapter.swapCursor(cursor);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        mMsgAdapter.swapCursor(null);
    }

    @Override
    public void onItemLongClick(View view, final long did,final int position) {
        new AlertDialog.Builder(getActivity()).setItems(new String[]{"删除对话"}, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                DatabaseHelper helper = new DatabaseHelper(getActivity(),"numa" + Global.getCurrentUid() + ".sqlite");
                getActivity().getContentResolver().delete(Numa.DialogColumns.CONTENT_URI,"_id="+did,null);
                //TODO network
                new RequestServerTask<BaseResponse>(BaseResponse.class, this, getString(R.string.progress_comment)) {
                    @Override
                    protected String requestServer() {
                        Map<String, Object> params = new HashMap<String, Object>();
                        params.put("did", did);
                        String requestUrl = String.format(NetworkConstants.MSG_DELETE,Global.getCurrentUid());
                        return HttpUtil.post(requestUrl, params);
                    }

                    @Override
                    protected void onSuccess(BaseResponse result) {
                        Utils.showSnackbar(rootView,"删除成功");
                    }
                }.start();

                //mMsgAdapter.notifyItemRemoved(position);
                refresh();
            }
        }).show();
    }


    public class SimpleAdapter extends UltimateViewAdapter<SimpleViewHolder> {

        Cursor mCursor;
        Object mParent;
        ChatItemClickListener listener;

        public SimpleAdapter(Object parent, Cursor cursor) {
            mCursor = cursor;
            mParent = parent;
        }

        public void setOnItemLongClickListener(ChatItemClickListener listener){
            this.listener = listener;
        }

        @Override
        public SimpleViewHolder getViewHolder(View view) {
            return new SimpleViewHolder(view, mParent, true,listener);
        }

        @Override
        public SimpleViewHolder onCreateViewHolder(ViewGroup parent) {
            View v = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.msg_list_item, parent, false);
            SimpleViewHolder vh = new SimpleViewHolder(v, mParent, false,listener);
            return vh;
        }

        @Override
        public int getAdapterItemCount() {
            if (mCursor == null)
                return 0;
            return mCursor.getCount();
        }

        @Override
        public long generateHeaderId(int i) {
            return 0;
        }

        public Cursor swapCursor(Cursor newCursor) {
            if (newCursor == mCursor) {
                return null;
            }
            Cursor oldCursor = mCursor;
            mCursor = newCursor;
            notifyDataSetChanged();
            return oldCursor;
        }

        @Override
        public void onBindViewHolder(SimpleViewHolder holder, int position) {
            if (mCursor != null && position < mCursor.getCount()) {
                mCursor.moveToPosition(position);
                holder.bindData(mCursor);
            }
        }

        @Override
        public RecyclerView.ViewHolder onCreateHeaderViewHolder(ViewGroup viewGroup) {
            return null;
        }

        @Override
        public void onBindHeaderViewHolder(RecyclerView.ViewHolder viewHolder, int i) {

        }
    }

    public class SimpleViewHolder extends BaseViewHolder implements View.OnLongClickListener {

        @Bind(R.id.avatar)
        public CircleImageView avatar;

        @Bind(R.id.name)
        public TextView name;

        @Bind(R.id.date)
        public TextView date;

        @Bind(R.id.text)
        public TextView dataText;

        @Bind(R.id.notice_point)
        ImageView noticePoint;

        private ChatItemClickListener listener;

        public SimpleViewHolder(View itemView, Object parent, boolean skip,ChatItemClickListener listener) {
            super(itemView, parent);
            if (skip)
                return;
            ButterKnife.bind(this, itemView);
            this.listener = listener;
            itemView.setOnClickListener(this);
            itemView.setOnLongClickListener(this);
            avatar.setBorderColor(Global.avatarColor);
            avatar.setBorderWidth(2);
            addOnClickListener(itemView);
            addOnClickListener(avatar);

        }


        String pic, nick, lastText;
        int uid;
        long time, cid;
        int badge;
        int type;
        public void bindData(Cursor cursor) {
            pic = cursor.getString(cursor.getColumnIndex("pic"));
            nick = cursor.getString(cursor.getColumnIndex("nick"));
            uid = cursor.getInt(cursor.getColumnIndex("uid"));
            lastText = cursor.getString(cursor.getColumnIndex("last_text"));
            time = cursor.getLong(cursor.getColumnIndex("last_time"));
            cid = cursor.getLong(cursor.getColumnIndex("_id"));
            badge = cursor.getInt(cursor.getColumnIndex("badge"));
            type = cursor.getInt(cursor.getColumnIndex("r_status"));
            if (type == Global.HAS_READ){
                noticePoint.setVisibility(View.INVISIBLE);
            }else {
                noticePoint.setVisibility(View.VISIBLE);
            }

            Picasso.with(getActivity()).load(pic).into(avatar);
            date.setText(Utils.getDatetimeStr(time));
            dataText.setText(lastText);
            name.setText(nick);
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.msg_view: {
                    noticePoint.setVisibility(View.INVISIBLE);
                    type = Global.HAS_READ;
                    final String url = String.format(NetworkConstants.MSG_READ_URL, Global.getCurrentUid());
                    final Map<String, Object> params = new LinkedHashMap<>();
                    params.put("did", String.valueOf(cid));
                    new Thread() {
                        @Override
                        public synchronized void start() {
                            HttpUtil.get(url, params);
                        }
                    }.start();
                    Intent intent = new Intent(getActivity(), ChatActivity.class);
                    intent.putExtra(ChatActivity.EXTRA_DID, cid);
                    startActivity(intent);
                }
                break;
                case R.id.avatar:
                    ProfileActivity.openProfile(getActivity(), uid);
                    break;
            }
        }

        @Override
        public boolean onLongClick(View v) {
            if(listener != null){
                listener.onItemLongClick(v, cid,getLayoutPosition());
            }
            return true;
        }
    }
}
